package com.clouddms.controller;

import com.clouddms.entity.User;
import com.clouddms.service.auth.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

/**
 * 用户API控制器
 * 提供用户信息管理相关的RESTful接口
 */
@RestController
@RequestMapping("/api/users")
@CrossOrigin(origins = "*", maxAge = 3600)
public class UserApiController {

    private static final Logger logger = LoggerFactory.getLogger(UserApiController.class);

    @Autowired
    private UserService userService;

    /**
     * 获取当前用户信息
     * @param request HTTP请求
     * @return 用户信息
     */
    @GetMapping("/profile")
    public ResponseEntity<Map<String, Object>> getUserProfile(HttpServletRequest request) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            Long userId = (Long) request.getAttribute("userId");
            if (userId == null) {
                response.put("success", false);
                response.put("message", "用户未认证");
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
            }

            Optional<User> userOpt = userService.findById(userId);
            if (!userOpt.isPresent()) {
                response.put("success", false);
                response.put("message", "用户不存在");
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(response);
            }

            User user = userOpt.get();
            
            // 构建用户信息响应
            Map<String, Object> userInfo = new HashMap<>();
            userInfo.put("userId", user.getUserId());
            userInfo.put("username", user.getUsername());
            userInfo.put("email", user.getEmail());
            userInfo.put("createdAt", user.getCreatedAt());
            userInfo.put("updatedAt", user.getUpdatedAt());
            userInfo.put("isActive", user.getIsActive());
            
            response.put("success", true);
            response.put("data", userInfo);
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            logger.error("获取用户信息失败", e);
            response.put("success", false);
            response.put("message", "获取用户信息失败");
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 更新用户信息
     * @param request HTTP请求
     * @param updateRequest 更新请求
     * @return 更新结果
     */
    @PutMapping("/profile")
    public ResponseEntity<Map<String, Object>> updateUserProfile(
            HttpServletRequest request,
            @RequestBody Map<String, Object> updateRequest) {
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            Long userId = (Long) request.getAttribute("userId");
            if (userId == null) {
                response.put("success", false);
                response.put("message", "用户未认证");
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
            }

            Optional<User> userOpt = userService.findById(userId);
            if (!userOpt.isPresent()) {
                response.put("success", false);
                response.put("message", "用户不存在");
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(response);
            }

            // 支持更新邮箱
            String newEmail = (String) updateRequest.get("email");
            if (newEmail != null && !newEmail.trim().isEmpty()) {
                // 邮箱格式验证
                if (!isValidEmail(newEmail)) {
                    response.put("success", false);
                    response.put("message", "邮箱格式不正确");
                    return ResponseEntity.badRequest().body(response);
                }
                
                // 检查邮箱是否已存在
                if (userService.existsByEmail(newEmail)) {
                    response.put("success", false);
                    response.put("message", "该邮箱已被使用");
                    return ResponseEntity.badRequest().body(response);
                }
                
                // 更新用户邮箱
                boolean success = userService.updateUserEmail(userId, newEmail);
                if (!success) {
                    response.put("success", false);
                    response.put("message", "更新邮箱失败");
                    return ResponseEntity.internalServerError().body(response);
                }
                
                logger.info("用户 {} 成功更新邮箱为: {}", userId, newEmail);
            }
            
            response.put("success", true);
            response.put("message", "用户信息更新成功");
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            logger.error("更新用户信息失败", e);
            response.put("success", false);
            response.put("message", "更新用户信息失败");
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 修改用户密码
     * @param request HTTP请求
     * @param passwordRequest 密码修改请求
     * @return 修改结果
     */
    @PutMapping("/change-password")
    public ResponseEntity<Map<String, Object>> changePassword(
            HttpServletRequest request,
            @RequestBody Map<String, Object> passwordRequest) {
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            Long userId = (Long) request.getAttribute("userId");
            if (userId == null) {
                response.put("success", false);
                response.put("message", "用户未认证");
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
            }

            String currentPassword = (String) passwordRequest.get("currentPassword");
            String newPassword = (String) passwordRequest.get("newPassword");
            String confirmPassword = (String) passwordRequest.get("confirmPassword");

            // 验证输入参数
            if (currentPassword == null || currentPassword.trim().isEmpty()) {
                response.put("success", false);
                response.put("message", "请输入当前密码");
                return ResponseEntity.badRequest().body(response);
            }

            if (newPassword == null || newPassword.trim().isEmpty()) {
                response.put("success", false);
                response.put("message", "请输入新密码");
                return ResponseEntity.badRequest().body(response);
            }

            if (confirmPassword == null || !newPassword.equals(confirmPassword)) {
                response.put("success", false);
                response.put("message", "新密码和确认密码不一致");
                return ResponseEntity.badRequest().body(response);
            }

            // 验证新密码强度
            if (newPassword.length() < 6) {
                response.put("success", false);
                response.put("message", "新密码长度不能少于6位");
                return ResponseEntity.badRequest().body(response);
            }

            // 更新密码（内部会验证当前密码）
            boolean success = userService.changePassword(userId, currentPassword, newPassword);
            if (!success) {
                response.put("success", false);
                response.put("message", "当前密码不正确或密码修改失败");
                return ResponseEntity.badRequest().body(response);
            }

            logger.info("用户 {} 成功修改密码", userId);
            
            response.put("success", true);
            response.put("message", "密码修改成功");
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            logger.error("修改密码失败", e);
            response.put("success", false);
            response.put("message", "修改密码失败");
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 验证邮箱格式
     * @param email 邮箱地址
     * @return 是否有效
     */
    private boolean isValidEmail(String email) {
        if (email == null || email.trim().isEmpty()) {
            return false;
        }
        
        String emailRegex = "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$";
        return email.matches(emailRegex);
    }
}